import sqlite3
from sqlite3 import Connection
class DatabaseDriver:
    def __init__(self, username: str = "", password: str = ""):
        self.connection = False
        if username == "" and password == "":
            self.conn: Connection = sqlite3.connect("../db/book.db")
            self.connection: bool = True
    def close(self):
        self.conn.close()
        self.connection = False
    def update(self, sql: str, log: bool = False):
        if self.connection:
            cursor = self.conn.cursor()
            if log:
                print("sql execute: {}".format(sql))
            c = cursor.execute(sql)
            if log:
                print("sql update count: {}".format(self.conn.total_changes))
            self.conn.commit()
            return self.conn.total_changes
        else:
            return Exception("数据库连接已关闭")
    def insert(self, sql: str, log: bool = False):
        return self.update(sql, bool)
    def delete(self, sql: str, log: bool = False):
        if self.connection:
            cursor = self.conn.cursor()
            if log:
                print("sql execute: {}".format(sql))
            c = cursor.execute(sql)
            if log:
                print("sql delete count: {}".format(self.conn.total_changes))
            self.conn.commit()
            return self.conn.total_changes
        else:
            raise Exception("数据库连接已关闭")
    def query_one(self, sql: str, log: bool = False):
        if self.connection:
            cursor = self.conn.cursor()
            if log:
                print("sql execute: {}".format(sql))
            c = cursor.execute(sql)
            self.conn.commit()
            data = c.fetchone()
            if log:
                print("sql execute result: {}".format(data))
            return data
        else:
            raise Exception("数据库连接已关闭")
    def query_all(self, sql: str, log: bool = False):
        if self.connection:
            cursor = self.conn.cursor()
            if log:
                print("sql execute: {}".format(sql))
            c = cursor.execute(sql)
            self.conn.commit()
            data = c.fetchall()
            if log:
                print("sql execute result lengths: {}".format(len(data)))
                for index, d in enumerate(data):
                    print("sql execute result{}: {}".format(index + 1, d))
            return data
        else:
            if __name__ == "__main__":
                db = DatabaseDriver()
                db.query_all(sql="select * from user where 1 = {}".format(1), log=True)